package com.yc.boottxx.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.boottxx.entity.Car;
import com.yc.boottxx.mapper.CarMapper;
import com.yc.boottxx.service.ICarService;
import com.yc.boottxx.service.BizException;
import com.yc.boottxx.util.Utils;
import com.yc.boottxx.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;
//import redis.clients.jedis.Jedis;
//import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 天下行租车-车辆表-10 前端控制器
 * </p>
 *
 * @author xl
 * @since 2024-05-07
 */
@RestController
@RequestMapping("/txx/car")
public class CarController {

    @Autowired
    CarMapper carMapper;
    @Autowired
    ICarService iCarService;

//    JedisPool jedisPool = new JedisPool("127.0.0.1",6379);

    @Resource(name = "stringRedisTemplate")
    StringRedisTemplate redisTemplate;

    ObjectMapper mapper = new ObjectMapper();

    @Autowired
    ICarService carService;

    @RequestMapping("query")
    List<Car> query(Car car) throws IOException {
        if(car.getPrice().intValue() == 3 &&
                Utils.isEmpty(car.getModel() ) &&
                Utils.isEmpty(car.getBrand()) &&
                Utils.isEmpty(car.getSort())
        ) {
//            Jedis jedis = jedisPool.getResource();
//            try{

                if(redisTemplate.hasKey("cars")){
                    String json = redisTemplate.opsForValue().get("cars");
                    //String json = jedis.get("cars");
                    List list = mapper.readValue(json, List.class);
                    System.out.println("--------- redis cars -----------");
                    return list;
                } else {
                    List<Car> list = carMapper.select(car);
                    String json = mapper.writeValueAsString(list);
                    redisTemplate.opsForValue().set("cars",json);
                    //jedis.set("cars",json);
                    System.out.println("--------- mysql cars -----------");
                    return list;
                }
//            }finally {
//                jedisPool.returnResource(jedis);
//            }
        } else {
            System.out.println("--------- mysql cars -----------");
            return carMapper.select(car);
        }
//        return carMapper.select(car);
    }

    @RequestMapping("queryBrand")
    List<String> queryBrand() throws IOException {
//        Jedis jedis = jedisPool.getResource();
//        try{
            if(redisTemplate.hasKey("brandItems")) {
                String json = redisTemplate.opsForValue().get("brandItems");
                List list = mapper.readValue(json, List.class);
                return list;
            } else {
                List<String> list = carMapper.selectBrand();
                String json = mapper.writeValueAsString(list);
                redisTemplate.opsForValue().set("brandItems",json);
                return list;
            }
//        }finally {
//            jedisPool.returnResource(jedis);
//        }

//        return carMapper.selectBrand();
    }

    @RequestMapping("selectCarDetail")
    Car selectCarDetail(String id){
        return carMapper.selectCarDetail(id);
    }


    @PostMapping("upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
        System.out.println("上传文件的字段名(请求参数) file.getName() = " + file.getName());
        System.out.println("上传文件名 file.getOriginalFilename() = " + file.getOriginalFilename());

        String NewName = UUID.randomUUID().toString();
        String fileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        File fileObj = new File("D:\\yc三期项目\\新教学视频\\5.14\\upload\\" + NewName + fileName);
        file.transferTo(fileObj);
        // 单文件上传
        return Result.ok("文件上传成功!",NewName+fileName);
    }
    @PostMapping("files")
    public Result upload1(@RequestParam("file") MultipartFile[] file){
        System.err.println("我到这里来啦!!!!");
        System.err.println(file.length);
        List<String> lists = new ArrayList<>();

        //System.out.println("上传的文件名 + ---files.getOriginalFilename() = " + file.getOriginalFilename());
        //多文件上传
        List<Object> list = new ArrayList<>();
        for (MultipartFile files : file){
            System.err.println("我在这里哦!!!!");
            if (!files.isEmpty()){
                try {
                    System.err.println("上传的文件名 + ---files.getOriginalFilename() = " + files.getOriginalFilename());
                    String newName = UUID.randomUUID().toString();
                    String suffx = files.getOriginalFilename().substring(files.getOriginalFilename().lastIndexOf("."));
                    File fileObj = new File("D:\\Idea-Workspace\\文件上传\\" + newName +suffx );
                    String iName = newName + suffx;
                    list.add(iName);
                    files.transferTo(fileObj);
                    for (int i = 0; i < list.size(); i++) {
                        System.out.println(list);

                        return Result.ok("文件上传成功！",iName);
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return Result.fail("文件上传失败",0);
    }

    @RequestMapping("addCar")
    public Result addCar(@Valid Car car, Errors errors,String imagePath){
        if (errors.hasErrors()){
            return Result.fail("字段验证失败",errors.getAllErrors());
        }
        try {
            System.out.println("imagePaths是 = " + imagePath);
            iCarService.Addcar(car,imagePath);

            return Result.ok("添加成功!!");
        } catch (BizException e) {
            String fieldName = e.getData().toString();
            errors.rejectValue(fieldName,fieldName + ".exists",e.getMessage());
            return Result.fail("字段验证失败",errors.getAllErrors());
        }
    }
}